<?php

namespace common\helpers;

use Yii;
use common\models\keyword\KeywordLibrary;

/**
 * Description of Words
 *
 * @author emhome
 */
class WordMatcher {

    public $dict = [];
    public $wordMaxLen = 0;

    public function __construct() {
        if (!extension_loaded('mbstring')) {
            exit('extension mbstring is not loaded');
        }
        mb_internal_encoding("UTF-8");
        $keywords = KeywordLibrary::find()->select(['id', 'text', 'length'])->asArray()->all();
        $this->dict = ArrayHelper::map($keywords, 'id', 'text');
        $len = max(ArrayHelper::getColumn($keywords, 'length'));
        $this->wordMaxLen = $len > $this->wordMaxLen ? $len : $this->wordMaxLen;
    }

    public function addWord($word, $key = null) {
        $len = mb_strlen($word);
        $this->wordMaxLen = $len > $this->wordMaxLen ? $len : $this->wordMaxLen;
//        $this->dict[$word] = 1;
        if ($key !== null) {
            $this->dict[$key] = $word;
        } else {
            array_push($this->dict, $word);
        }
    }

    public function removeWord($word) {
        $key = array_search($word, $this->dict);
        unset($this->dict[$key]);
    }

    public function match($string, &$matched) {
        if (mb_strlen($string) < 1) {
            return;
        }
        $len = $this->wordMaxLen;
        while ($len > 0) {
            $substr = mb_substr($string, 0, $len);
            $key = array_search($substr, $this->dict);
            if ($key !== false) {
                $matched[$key] = $substr;
                break;
            } else {
                $len--;
            }
        }
        if ($len == 0) {
            $len = 1;
        }
        $this->match(mb_substr($string, $len), $matched);
    }

}
